<script setup lang="ts">
import Qrcode from 'qrcode.vue';
import ysn_kt from "./public/images/ysn_kt.png"
import { onMounted, type Reactive } from 'vue';
import {useCookie} from "nuxt/app"

//cookie
const  tokenCookie = useCookie('token')

const router = useRouter()

const qrcodeRef = ref(null)//二维码的refs(id)
const userAccoutRegRef = ref(null) //用户注册按键refs
const userAccoutLoginRef = ref(null) //用户登陆按键refs

//状态是否是登陆状态
const statusIsLogin = ref(false)
const loginText = ref("")
const user_id = ref("")

//是否是注册或者登陆
const isLoginPage:Ref<boolean> = ref(true)

//定时器
let intervalId:any = null

interface phoneInter {
  phone:string, //一般为唯一值
  can1:string,//验证码
}

interface phoneLoginInter {
  phone:string, //一般为唯一值
  password:string,//验证码
  token:string,//token
}

//用户注册请求缓存
const phoneReactive:Reactive<phoneInter> = reactive({
  phone:"",
  can1:""
})
//用户登陆请求缓存
const userLoginReactive:Reactive<phoneLoginInter> = reactive({
  phone: "",
  password: "",
  token:""
})

onMounted(async()=>{
  if(tokenCookie.value != null){
    console.log('tokenCookie is',tokenCookie.value)
    userLoginReactive.token=tokenCookie.value
    const one = await fetch('/api/decodeJWT',{
      method:"POST",
      body:JSON.stringify(userLoginReactive),
      headers:{
        'Content-Type':"application/json"
      }
    }).then(res=>{return res.json()}).then(async (data:any)=>{
      console.log(data)
      userLoginReactive.phone = await data.data.account
      userLoginReactive.password = await data.data.password
      // statusIsLogin.value = await true
    }).catch((err:any)=>console.log(err))

    const two = await fetch('/api/select/selectUserByPhone',{
      method:"POST",
      body:JSON.stringify(userLoginReactive),
      headers:{
        'Content-Type':"application/json"
      }
    }).then(res=>{return res.json()}).then(async (data:any)=>{
      console.log(data)
      if(tokenCookie.value == 'undefined'){
        statusIsLogin.value = await true
        loginText.value = "登录"
      }else{
        statusIsLogin.value = await true
        loginText.value = await data.data.name
      }
      user_id.value = await data.data._id
      
    }).catch((err:any)=>console.log(err))
  }
})

//
const drawQRWithLogo = (text:any, logoSrc:any) => {
  const canvas = document.createElement('canvas')
  Qrcode.toCanvas(canvas, text, function (error:any) {
    if (error) console.error(error)
    const ctx = canvas.getContext('2d')
    const logo = new Image()
    logo.src = logoSrc
    logo.onload = function () {
      const logoSize = canvas.width * 0.2 // 调整logo大小
      const logoX = (canvas.width - logoSize) / 2
      const logoY = (canvas.height - logoSize) / 2
      ctx?.drawImage(logo, logoX, logoY, logoSize, logoSize)
    }
  })
}

const isLoginShow = ref(false)
//扫码配置
const qrcodeValue = ref("hello world")
const qrcodeSize = ref(200)
const qrcodeColor = ref("#09fff7")
const qrcodeBack = ref("#ffffff")
// const logoSrc = "./public/images/ysn_kt.png"
const logoMargin = 5 // Logo 边距
const logoScale = 0.2 // Logo 缩放比例

//发送按钮
const countdown = ref(0)//禁用倒计时初始化
const buttonDisable = ref(false) //是否禁用

//打开登陆
function goToLogin(){
  isLoginShow.value = true
  // new Qrcode('')
}
//关闭登陆
function closeLogin(){
  isLoginShow.value = false
}

//用户注册按钮
function thisUserAccoutReg(){
  // console.log(userAccoutRef.value)
  userAccoutRegRef.value.style.color = "#f00"
  userAccoutLoginRef.value.style.color = "#000"
  isLoginPage.value = false
}

//用户登陆按钮
function thisUserAccoutLogin(){
  // console.log(userAccoutRef.value)
  userAccoutRegRef.value.style.color = "#000"
  userAccoutLoginRef.value.style.color = "#f00"
  isLoginPage.value = true
}

//发送验证码
async function postSubCan(){
  countdown.value = await 31//禁用倒计时,比如如果想设置n秒才可以再次请求，那么你得设置为(n+1)的值
  intervalId = setInterval(async() => {
    buttonDisable.value = await true
    if (countdown.value > 0) {
      countdown.value--; // 每次减少1秒
    } else {
      clearInterval(intervalId); // 清除定时器
      buttonDisable.value = false; // 重新启用按钮
    }
  }, 1000); // 每秒更新一次
  fetch('/api/getPhone',{
    method: 'POST',
    body: JSON.stringify(phoneReactive),
    headers:{
      'Content-Type': 'application/json'
    }
  }).then(async res =>{return res.json()}).then(async(data:any) => {
    console.log(data)
    //弹出验证码
    if(data.message.can != undefined){
      alert(`你的验证码是:${data.message.can}`)
    }else{
      alert("提示:你没有输入手机号,不能发送请求")
      phoneReactive.phone = ""
      phoneReactive.can1 = ""
      // isLoginShow.value = false
      //清除定时器和值
      countdown.value = 0
      intervalId = null
      clearInterval(intervalId); // 清除定时器
    }
  }).catch(err=>console.log(err))
}

//注册用户
function postRegisterUser(){
  if(phoneReactive.phone != "" && phoneReactive.can1 != ""){
    fetch('/api/registerUser',{
      method:'POST',
      body:JSON.stringify(phoneReactive),
      headers:{
        'Content-Type':"application/json"
      }
    }).then(async res =>{return res.json()}).then(async(data:any) => {
      console.log(data)
      if(data.message == "你已经注册过账号"){
        alert("你已经注册过账号,请登录")
        thisUserAccoutLogin()
      }else if(data.message == "验证码为空"){
        alert("验证码为空")
      }else{
        alert("注册成功")
        phoneReactive.phone = ""
        phoneReactive.can1 = ""
        isLoginShow.value = false
      }
      
      //清除定时器和值
      countdown.value = 0
      intervalId = null
      clearInterval(intervalId); // 清除定时器
    }).catch(err=>console.log(err))
  }else{
    alert("注册的手机号或者验证码是空")
  }
}

//用户登陆
function userLoginBtn(){
  fetch('/api/loginUser',{
    method:"POST",
    body:JSON.stringify(userLoginReactive),
    headers:{
      'Content-Type':"application/json"
    }
  }).then(res=>{return res.json()}).then(async (data:any)=>{
    console.log(data.token)
    
    user_id.value = await data.data._id
    isLoginShow.value = await false
    tokenCookie.value = await data.token
    if(data.token === 'undefined'){
      statusIsLogin.value = await false
      loginText.value = "登录"
    }else{
      statusIsLogin.value = await true
      loginText.value = await data.data.name
    }
  }).catch((err:any)=>console.log(err))
}

//用户详细页面
function openUser(){
  // router.push(`/${user_id.value}/${loginText.value}`)
  if(tokenCookie.value != 'undefined'){
    router.push(`/user/${user_id.value}`)
  }else{}
}

//用户投稿页
function goToUserTouGaoBtn(){
  if(user_id.value != ""){
    router.push(`/video/${user_id.value}/upload`)
  }else{
    alert("请先登录")
  }
}
</script>

<template>
  <!-- 登陆页面 -->
  <div ref="loginRef" v-if="isLoginShow" class="loginClass">
    <div class="masterBox">
      <div @click="closeLogin()" class="closeBtn">关闭</div>
      <div class="scanNameTitle">扫码登陆</div>
      <div class="qrcodeClass">
        <qrcode :value="qrcodeValue" 
        :foreground="qrcodeColor"
        :margin="1"
        :logo-src="ysn_kt" 
        :logo-scale="logoScale"
        :logo-margin="logoMargin"
        :size="qrcodeSize" class="qrcodeMaster" 
        ref="qrcodeRef"/>
        <div class="phoneRegNameTitle"
        @click="thisUserAccoutReg()" ref="userAccoutRegRef">用户注册</div>
        <div class="phoneLoginNameTitle"
        @click="thisUserAccoutLogin()" ref="userAccoutLoginRef">用户登陆</div>
        <!-- 用户注册 -->
        <div class="phoneRegMaster" v-if="!isLoginPage">
          <input type="text" v-model="phoneReactive.phone" placeholder="手机号" />
          <input type="text" v-model="phoneReactive.can1" placeholder="验证码" />
          <button @click="postSubCan" :disabled="buttonDisable">{{ countdown > 0 ? `${countdown}发送验证码` : '发送验证码' }}</button><br />
          <button @click="postRegisterUser">注册</button>
        </div>
        <!-- 用户登陆 -->
        <div class="phoneRegMaster" v-else>
          <input type="text" v-model="userLoginReactive.phone" placeholder="请输入手机号" /><br />
          <input type="password" v-model="userLoginReactive.password" placeholder="请输入密码(默认是123456)">
          <button @click="userLoginBtn">登陆</button>
        </div>

      </div>
    </div>
  </div>

  <!-- 主页 -->
  <div class="">
    <nuxt-link to="/" class="">首页</nuxt-link>
    <nuxt-link to="/test">测试</nuxt-link>
    <span @click="goToLogin()" class="loginBtn" v-if="statusIsLogin == false">登陆</span>
    <span class="loginBtn" v-else @click="openUser">{{ loginText }}</span>
    <div class="tougao" @click="goToUserTouGaoBtn">投稿</div>
  </div>
  <div>
    <nuxt-page></nuxt-page>
  </div>
</template>

<style scoped>
.loginClass{
  position: absolute;
  left: 0;
  top: 0;
  width: calc(100%);
  height: calc(100%);
  background: rgba(0, 0, 0, .3);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.loginBtn{
  position: absolute;
  left: 200px;
  top: 0;
  width: 25px;
  height: 25px;
  font-size: 10px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(50, 50, 255, 1);
  color: #fff;
  user-select: none;
  cursor: pointer;
}
.masterBox{
  width: 1000px;
  height: 650px;
  background: rgba(255, 255, 255, 1);
  border-radius: 10px;
}
.closeBtn{
  position: absolute;
  right: 20%;
  top: 20%;
  user-select: none;
  cursor: pointer;
}
.qrcodeClass{
  position: relative;
  left: 100px;
  top: 200px;
  width: 200px;
  height: 200px;
  /* background: rgba(0, 255, 200, 1); */
}
.qrcodeMaster{
  border: 2px solid #09fff7; /* 添加边框 */
  padding: 10px; /* 添加内边距 */
  border-radius: 15px;
}
.scanNameTitle{
  position: absolute;
  left: 26%;
  top: 30%;
  font-size: calc(20px);
}
/* 注册样式 */
.phoneRegNameTitle{
  position: absolute;
  left: 190%;
  top: -40%;
  width: 40%;
  font-size: 20px;
  cursor: pointer;
  user-select: none;
}
.phoneRegMaster{
  position: absolute;
  left: 150%;
  top: -5%;
  width: 150%;
  height: 100%;
}
/*用户登陆样式 */
.phoneLoginNameTitle{
  position: absolute;
  left: 270%;
  top: -40%;
  width: 40%;
  font-size: 20px;
  cursor: pointer;
  user-select: none;
  color: #f00;/** 默认为红色*/
}

.tougao{
  position: absolute;
  left: 700px;
  top: 0;
  width: 100px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 50, 50, .8);
  color: #fff;
  border-radius: 10px;
  cursor: pointer;
  user-select: none;
}
</style>
